/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.camachosanchez.util;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.Pipeline;
import com.itextpdf.tool.xml.XMLWorker;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.tool.xml.exceptions.CssResolverException;
import com.itextpdf.tool.xml.html.Tags;
import com.itextpdf.tool.xml.parser.XMLParser;
import com.itextpdf.tool.xml.pipeline.css.CSSResolver;
import com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline;
import com.itextpdf.tool.xml.pipeline.end.PdfWriterPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import javax.swing.table.DefaultTableModel;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;

/**
 *
 * @author Zully
 */
public class ReportUtil {

    public static PdfPCell getCelda(String text, int colspan, int rowspan, BaseColor color, int alineado, float borde, int tam, int font) {
        PdfPCell celda1 = new PdfPCell(new Phrase(text, FontFactory.getFont(BaseFont.COURIER, // fuente
                tam, // tamaño
                font, // estilo 0->normal, 1->negrita, 2->cursiva, 3->cursiva negrita, 4->subrayado
                BaseColor.GRAY.darker())));
        celda1.setRowspan(rowspan);
        celda1.setColspan(colspan);
        celda1.setHorizontalAlignment(alineado);
//         alineado:
//        ALIGN_LEFT = 0
//        ALIGN_CENTER = 1
//        ALIGN_RIGHT = 2
//        ALIGN_JUSTIFIED = 3
        celda1.setVerticalAlignment(Element.ALIGN_MIDDLE);//todos centrados verticalmente
        celda1.setBackgroundColor(color);
        celda1.setBorderWidth(borde);
        return celda1;
    }

    public static PdfPCell getCeldaBorde(String text, int colspan, int rowspan, BaseColor color, int alineado, float borde, int tam, int font) {
        PdfPCell celda1 = new PdfPCell(new Phrase(text, FontFactory.getFont(BaseFont.COURIER, // fuente
                tam, // tamaño
                font, // estilo 0->normal, 1->negrita, 2->cursiva, 3->cursiva negrita, 4->subrayado
                BaseColor.GRAY.darker())));
        celda1.setRowspan(rowspan);
        celda1.setColspan(colspan);
        celda1.setHorizontalAlignment(alineado);
//         alineado:
//        ALIGN_LEFT = 0
//        ALIGN_CENTER = 1
//        ALIGN_RIGHT = 2
//        ALIGN_JUSTIFIED = 3
        celda1.setVerticalAlignment(Element.ALIGN_MIDDLE);//todos centrados verticalmente
//         celda1.setBackgroundColor(color);
//         celda1.setBorderWidth(borde);
        celda1.setBorder(Rectangle.NO_BORDER);
        return celda1;
    }

    public static PdfPCell getCelda(String text, int colspan, int rowspan, BaseColor color, BaseColor colorFuente, int alineado, float borde, int tam, int font) {
        PdfPCell celda1 = new PdfPCell(new Phrase(text, FontFactory.getFont(BaseFont.COURIER, // fuente
                tam, // tamaño
                font, // estilo 0->normal, 1->negrita, 2->cursiva, 3->cursiva negrita, 4->subrayado
                colorFuente)));
        celda1.setRowspan(rowspan);
        celda1.setColspan(colspan);
        celda1.setHorizontalAlignment(alineado);
//         alineado:
//        ALIGN_LEFT = 0
//        ALIGN_CENTER = 1
//        ALIGN_RIGHT = 2
//        ALIGN_JUSTIFIED = 3
        celda1.setVerticalAlignment(Element.ALIGN_MIDDLE);//todos centrados verticalmente
        celda1.setBackgroundColor(color);
        celda1.setBorderWidth(borde);
        return celda1;
    }

    public static File deHtmlAPdf(String txtHtml, String nombrePdf) {
        File pdfFile = null;
        try {
            Document document = new Document(PageSize.A4);
            FileOutputStream fos = new FileOutputStream(nombrePdf);
            pdfFile = new File(nombrePdf);

            PdfWriter pdfWriter = PdfWriter.getInstance(document, fos);
            document.open();
            HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
            htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
            CSSResolver cssResolver = XMLWorkerHelper.getInstance().getDefaultCssResolver(true);
            cssResolver.addCss("table {font-size: 9px;}", true);
            Pipeline<?> pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, pdfWriter)));
            XMLWorker worker = new XMLWorker(pipeline, true);
            XMLParser xmlParser = new XMLParser(worker);
            xmlParser.parse(new StringReader(txtHtml));
            document.close();
            fos.flush();
            fos.close();
        } catch (CssResolverException ex) {
            ex.printStackTrace();
        } catch (DocumentException ex) {
            ex.printStackTrace();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return pdfFile;
    }

    private static CellStyle getEstiloTitulo(HSSFWorkbook libro) {
        final CellStyle cellStyle = libro.createCellStyle();
        final org.apache.poi.ss.usermodel.Font cellFont = libro.createFont();
        cellFont.setColor(IndexedColors.WHITE.getIndex());
        cellFont.setBoldweight(org.apache.poi.ss.usermodel.Font.BOLDWEIGHT_NORMAL);
        cellStyle.setFont(cellFont);
        cellStyle.setFillForegroundColor(IndexedColors.BLUE_GREY.getIndex());
        cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
        cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
        return cellStyle;
    }

    public static void generarReporteExcel(String nombreArchivo, DefaultTableModel modeloTabla) throws Exception {
        HSSFWorkbook libro = new HSSFWorkbook();
//        CellStyleManager styleManager = new CellStyleManager(libro);
        HSSFSheet hoja = libro.createSheet();
        HSSFRow head = hoja.createRow(0);
        CellStyle estiloTitulo;
        estiloTitulo = getEstiloTitulo(libro);
        int numeroColumnas = modeloTabla.getColumnCount();
        HSSFCell celda;
        HSSFRichTextString texto;
        for (int i = 0; i < numeroColumnas; i++) {
            String nombreColumna = modeloTabla.getColumnName(i);
            celda = head.createCell(i);
            celda.setCellStyle(libro.createCellStyle());
            celda.setCellStyle(estiloTitulo);
            texto = new HSSFRichTextString(nombreColumna);
            celda.setCellValue(texto);
        }
        CellStyle cellStyle = libro.createCellStyle();
        for (int i = 0; i < modeloTabla.getRowCount(); i++) {
            HSSFRow body = hoja.createRow(i + 1);
            for (int j = 0; j < numeroColumnas; j++) {
                celda = body.createCell(j);
                Object valor = modeloTabla.getValueAt(i, j);
                if (valor == null) {
                    valor = "";
                }
                String valorDeCelda = valor.toString();
                cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
                celda.setCellStyle(cellStyle);
                texto = new HSSFRichTextString(valorDeCelda);
                celda.setCellValue(texto);
            }
        }
        for (int i = 0; i < numeroColumnas; i++) {
            hoja.autoSizeColumn(i);
        }
        FileOutputStream elFichero = new FileOutputStream(nombreArchivo);
        libro.write(elFichero);
        elFichero.close();
        Runtime.getRuntime().exec("cmd.exe /c start " + nombreArchivo);
    }

    //*********************** NUEVOS **************************************
    public static PdfPTable obtenerCabeceraTabla(String titulo) {
        PdfPTable cabecera = new PdfPTable(1);
        try {
            cabecera.setWidthPercentage(100);
            PdfPCell cell;
            //Font fuenteTitulos = new Font(Font.FontFamily.TIMES_ROMAN, 10.0f, Font.BOLD);
            BaseFont bf1 = BaseFont.createFont("cour.ttf", BaseFont.CP1252, BaseFont.EMBEDDED);
            Font fuenteTitulos = new Font(bf1, 12);
            fuenteTitulos.setStyle(Font.BOLD);
            Chunk chunk = new Chunk(titulo, fuenteTitulos);
            cell = new PdfPCell(new Phrase(chunk));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setBorder(0);
            cabecera.addCell(cell);
            return cabecera;
        } catch (Exception ex) {
            ex.printStackTrace();
            cabecera = null;
        } finally {
            return cabecera;
        }
    }

    public static PdfPCell obtenerCeldaSinBorde(String valor, Font fuente, int colspan) {
        PdfPCell cell;
        Chunk chunk;
        if (fuente != null) {
            chunk = new Chunk(valor, fuente);
        } else {
            chunk = new Chunk(valor);
        }
        cell = new PdfPCell(new Phrase(chunk));
        cell.setColspan(colspan);
        cell.setBorder(0);
        return cell;
    }

    public static PdfPCell obtenerCeldaCabeceraTabla(String valor, Font fuente, int colspan, BaseColor color) {
        PdfPCell cell;
        Chunk chunk;
        if (fuente != null) {
            chunk = new Chunk(valor, fuente);
        } else {
            chunk = new Chunk(valor);
        }
        cell = new PdfPCell(new Phrase(chunk));
        cell.setColspan(colspan);
        cell.setBackgroundColor(color);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        return cell;
    }

    public static PdfPCell obtenerCeldaCabeceraTabla(String valor, Font fuente, int colspan) {
        PdfPCell cell;
        Chunk chunk;
        if (fuente != null) {
            chunk = new Chunk(valor, fuente);
        } else {
            chunk = new Chunk(valor);
        }
        cell = new PdfPCell(new Phrase(chunk));
        cell.setColspan(colspan);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        return cell;
    }

    public static PdfPCell obtenerCeldaNumerica(String valor, Font fuente, int colspan) {
        PdfPCell cell;
        Chunk chunk;
        if (fuente != null) {
            chunk = new Chunk(valor + " ", fuente);
        } else {
            chunk = new Chunk(valor + " ");
        }
        cell = new PdfPCell(new Phrase(chunk));
        cell.setColspan(colspan);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        return cell;
    }
    
    public static PdfPCell obtenerCeldaNumerica(String valor, Font fuente, int colspan, BaseColor color) {
        PdfPCell cell;
        Chunk chunk;
        if (fuente != null) {
            chunk = new Chunk(valor + " ", fuente);
        } else {
            chunk = new Chunk(valor + " ");
        }
        cell = new PdfPCell(new Phrase(chunk));
        cell.setColspan(colspan);
        cell.setBackgroundColor(color);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        return cell;
    }

    public static PdfPCell obtenerCeldaTexto(String valor, Font fuente, int colspan) {
        PdfPCell cell;
        Chunk chunk;
        if (fuente != null) {
            chunk = new Chunk(valor, fuente);
        } else {
            chunk = new Chunk(valor);
        }
        cell = new PdfPCell(new Phrase(chunk));
        cell.setColspan(colspan);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        return cell;
    }
    //*********************************************************************
}
